/*!
 * \file test_wt_latency_modules.cpp
 * \project WonderTrader
 *
 * \author AI Assistant
 * \date 2024/12/01
 * 
 * \brief WtLatency模块的综合测试文件
 * 
 * \details 本文件包含对WtLatencyUFT和WtLatencyHFT模块的全面测试，
 *          涵盖延迟测量、性能监控、统计分析等核心功能。
 *          测试用例包括功能测试、性能测试、精度测试和边界条件测试。
 */

#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include <memory>
#include <thread>
#include <chrono>
#include <atomic>
#include <vector>
#include <string>
#include <map>
#include <algorithm>
#include <numeric>

// 模拟WtLatency相关头文件和类
namespace {

// 延迟测量点枚举
enum class LatencyPoint {
    ORDER_RECEIVED,     // 订单接收
    ORDER_VALIDATED,    // 订单验证
    ORDER_SENT,         // 订单发送
    ORDER_CONFIRMED,    // 订单确认
    MARKET_DATA_RECEIVED, // 行情接收
    MARKET_DATA_PROCESSED // 行情处理
};

// 延迟记录结构
struct LatencyRecord {
    uint64_t timestamp_ns;  // 纳秒时间戳
    LatencyPoint point;     // 测量点
    std::string tag;        // 标签
    uint64_t sequence_id;   // 序列号
    
    LatencyRecord(uint64_t ts, LatencyPoint pt, const std::string& t, uint64_t seq)
        : timestamp_ns(ts), point(pt), tag(t), sequence_id(seq) {}
};

// 延迟统计结构
struct LatencyStats {
    double min_latency_us;    // 最小延迟(微秒)
    double max_latency_us;    // 最大延迟(微秒)
    double avg_latency_us;    // 平均延迟(微秒)
    double p50_latency_us;    // 50分位延迟
    double p95_latency_us;    // 95分位延迟
    double p99_latency_us;    // 99分位延迟
    uint64_t sample_count;    // 样本数量
    
    LatencyStats() : min_latency_us(0), max_latency_us(0), avg_latency_us(0),
                    p50_latency_us(0), p95_latency_us(0), p99_latency_us(0), sample_count(0) {}
};

// 模拟WtLatencyUFT类 (超高频交易延迟测量)
class MockWtLatencyUFT {
public:
    MockWtLatencyUFT() : _initialized(false), _measuring(false), _sequence_counter(0) {}
    virtual ~MockWtLatencyUFT() = default;

    // 初始化接口
    bool init(const std::string& config_path) {
        _initialized = true;
        _measuring = false;
        return true;
    }

    // 开始测量
    bool start_measuring() {
        if (!_initialized) return false;
        _measuring = true;
        _start_time = get_current_time_ns();
        return true;
    }

    // 停止测量
    void stop_measuring() {
        _measuring = false;
    }

    // 记录延迟点
    bool record_latency_point(LatencyPoint point, const std::string& tag = "") {
        if (!_measuring) return false;
        
        uint64_t timestamp = get_current_time_ns();
        uint64_t seq_id = ++_sequence_counter;
        
        std::lock_guard<std::mutex> lock(_mutex);
        _records.emplace_back(timestamp, point, tag, seq_id);
        return true;
    }

    // 计算两点间延迟
    double calculate_latency_between_points(LatencyPoint start_point, LatencyPoint end_point,
                                          uint64_t sequence_id) {
        std::lock_guard<std::mutex> lock(_mutex);
        
        uint64_t start_time = 0, end_time = 0;
        bool found_start = false, found_end = false;
        
        for (const auto& record : _records) {
            if (record.sequence_id == sequence_id) {
                if (record.point == start_point) {
                    start_time = record.timestamp_ns;
                    found_start = true;
                }
                if (record.point == end_point) {
                    end_time = record.timestamp_ns;
                    found_end = true;
                }
            }
        }
        
        if (found_start && found_end && end_time > start_time) {
            return (end_time - start_time) / 1000.0; // 转换为微秒
        }
        return -1.0; // 表示无效
    }

    // 获取延迟统计 - 基于标签匹配记录
    LatencyStats get_latency_stats(LatencyPoint start_point, LatencyPoint end_point) {
        std::lock_guard<std::mutex> lock(_mutex);
        
        std::vector<double> latencies;
        std::map<std::string, uint64_t> start_times, end_times;
        
        // 收集同标签的开始和结束时间
        for (const auto& record : _records) {
            if (record.point == start_point) {
                start_times[record.tag] = record.timestamp_ns;
            }
            if (record.point == end_point) {
                end_times[record.tag] = record.timestamp_ns;
            }
        }
        
        // 计算延迟
        for (const auto& start_pair : start_times) {
            const std::string& tag = start_pair.first;
            uint64_t start_time = start_pair.second;
            
            auto end_it = end_times.find(tag);
            if (end_it != end_times.end() && end_it->second > start_time) {
                double latency_us = (end_it->second - start_time) / 1000.0;
                latencies.push_back(latency_us);
            }
        }
        
        return calculate_stats(latencies);
    }

    // 基于标签计算延迟
    double calculate_latency_by_tag(LatencyPoint start_point, LatencyPoint end_point,
                                   const std::string& tag) {
        std::lock_guard<std::mutex> lock(_mutex);
        
        uint64_t start_time = 0, end_time = 0;
        bool found_start = false, found_end = false;
        
        // 正向查找匹配的记录
        for (const auto& record : _records) {
            if (record.tag == tag) {
                if (record.point == start_point) {
                    start_time = record.timestamp_ns;
                    found_start = true;
                }
                if (record.point == end_point && found_start) {
                    end_time = record.timestamp_ns;
                    found_end = true;
                    break; // 找到匹配的一对就退出
                }
            }
        }
        
        if (found_start && found_end && end_time > start_time) {
            return (end_time - start_time) / 1000.0; // 转换为微秒
        }
        return -1.0; // 表示无效
    }

    // 清除记录
    void clear_records() {
        std::lock_guard<std::mutex> lock(_mutex);
        _records.clear();
        _sequence_counter = 0;
    }

    // 状态查询
    bool is_initialized() const { return _initialized; }
    bool is_measuring() const { return _measuring; }
    size_t get_record_count() const {
        std::lock_guard<std::mutex> lock(_mutex);
        return _records.size();
    }

    // 调试方法：获取所有记录
    std::vector<LatencyRecord> get_all_records() const {
        std::lock_guard<std::mutex> lock(_mutex);
        return _records;
    }

public: // Temporary for debugging
    std::atomic<uint64_t> _sequence_counter;
    std::vector<LatencyRecord> _records;
    mutable std::mutex _mutex;

private:
    uint64_t get_current_time_ns() {
        auto now = std::chrono::high_resolution_clock::now();
        return std::chrono::duration_cast<std::chrono::nanoseconds>(now.time_since_epoch()).count();
    }

    LatencyStats calculate_stats(std::vector<double>& latencies) {
        LatencyStats stats;
        
        if (latencies.empty()) {
            return stats;
        }
        
        std::sort(latencies.begin(), latencies.end());
        
        stats.sample_count = latencies.size();
        stats.min_latency_us = latencies.front();
        stats.max_latency_us = latencies.back();
        stats.avg_latency_us = std::accumulate(latencies.begin(), latencies.end(), 0.0) / latencies.size();
        
        // 计算分位数
        size_t p50_idx = latencies.size() * 50 / 100;
        size_t p95_idx = latencies.size() * 95 / 100;
        size_t p99_idx = latencies.size() * 99 / 100;
        
        stats.p50_latency_us = latencies[std::min(p50_idx, latencies.size() - 1)];
        stats.p95_latency_us = latencies[std::min(p95_idx, latencies.size() - 1)];
        stats.p99_latency_us = latencies[std::min(p99_idx, latencies.size() - 1)];
        
        return stats;
    }

private:
    bool _initialized;
    bool _measuring;
    uint64_t _start_time;
};

// 模拟WtLatencyHFT类 (高频交易延迟测量)
class MockWtLatencyHFT {
public:
    MockWtLatencyHFT() : _initialized(false), _monitoring(false) {}
    virtual ~MockWtLatencyHFT() = default;

    // 初始化接口
    bool init(const std::string& config_path, int buffer_size = 10000) {
        _buffer_size = buffer_size;
        _initialized = true;
        _monitoring = false;
        return true;
    }

    // 开始监控
    bool start_monitoring() {
        if (!_initialized) return false;
        _monitoring = true;
        _monitor_thread = std::thread(&MockWtLatencyHFT::monitor_loop, this);
        return true;
    }

    // 停止监控
    void stop_monitoring() {
        _monitoring = false;
        if (_monitor_thread.joinable()) {
            _monitor_thread.join();
        }
    }

    // 记录网络延迟
    void record_network_latency(double latency_us, const std::string& endpoint) {
        if (!_monitoring) return;
        
        std::lock_guard<std::mutex> lock(_mutex);
        _network_latencies[endpoint].push_back(latency_us);
        
        // 保持缓冲区大小
        if (_network_latencies[endpoint].size() > _buffer_size) {
            _network_latencies[endpoint].erase(_network_latencies[endpoint].begin());
        }
    }

    // 记录处理延迟
    void record_processing_latency(double latency_us, const std::string& component) {
        if (!_monitoring) return;
        
        std::lock_guard<std::mutex> lock(_mutex);
        _processing_latencies[component].push_back(latency_us);
        
        // 保持缓冲区大小
        if (_processing_latencies[component].size() > _buffer_size) {
            _processing_latencies[component].erase(_processing_latencies[component].begin());
        }
    }

    // 获取网络延迟统计
    LatencyStats get_network_stats(const std::string& endpoint) {
        std::lock_guard<std::mutex> lock(_mutex);
        
        auto it = _network_latencies.find(endpoint);
        if (it != _network_latencies.end()) {
            std::vector<double> latencies = it->second;
            return calculate_stats(latencies);
        }
        return LatencyStats();
    }

    // 获取处理延迟统计
    LatencyStats get_processing_stats(const std::string& component) {
        std::lock_guard<std::mutex> lock(_mutex);
        
        auto it = _processing_latencies.find(component);
        if (it != _processing_latencies.end()) {
            std::vector<double> latencies = it->second;
            return calculate_stats(latencies);
        }
        return LatencyStats();
    }

    // 获取所有端点列表
    std::vector<std::string> get_monitored_endpoints() {
        std::lock_guard<std::mutex> lock(_mutex);
        std::vector<std::string> endpoints;
        for (const auto& pair : _network_latencies) {
            endpoints.push_back(pair.first);
        }
        return endpoints;
    }

    // 获取所有组件列表
    std::vector<std::string> get_monitored_components() {
        std::lock_guard<std::mutex> lock(_mutex);
        std::vector<std::string> components;
        for (const auto& pair : _processing_latencies) {
            components.push_back(pair.first);
        }
        return components;
    }

    // 状态查询
    bool is_initialized() const { return _initialized; }
    bool is_monitoring() const { return _monitoring; }

private:
    void monitor_loop() {
        while (_monitoring) {
            // 模拟监控工作
            std::this_thread::sleep_for(std::chrono::milliseconds(100));
            
            // 模拟自动记录一些延迟数据
            record_network_latency(50.0 + (rand() % 100) * 0.1, "exchange_gateway");
            record_processing_latency(10.0 + (rand() % 50) * 0.1, "order_processor");
        }
    }

    LatencyStats calculate_stats(std::vector<double>& latencies) {
        LatencyStats stats;
        
        if (latencies.empty()) {
            return stats;
        }
        
        std::sort(latencies.begin(), latencies.end());
        
        stats.sample_count = latencies.size();
        stats.min_latency_us = latencies.front();
        stats.max_latency_us = latencies.back();
        stats.avg_latency_us = std::accumulate(latencies.begin(), latencies.end(), 0.0) / latencies.size();
        
        // 计算分位数
        size_t p50_idx = latencies.size() * 50 / 100;
        size_t p95_idx = latencies.size() * 95 / 100;
        size_t p99_idx = latencies.size() * 99 / 100;
        
        stats.p50_latency_us = latencies[std::min(p50_idx, latencies.size() - 1)];
        stats.p95_latency_us = latencies[std::min(p95_idx, latencies.size() - 1)];
        stats.p99_latency_us = latencies[std::min(p99_idx, latencies.size() - 1)];
        
        return stats;
    }

private:
    bool _initialized;
    bool _monitoring;
    size_t _buffer_size;
    std::thread _monitor_thread;
    std::map<std::string, std::vector<double>> _network_latencies;
    std::map<std::string, std::vector<double>> _processing_latencies;
    mutable std::mutex _mutex;
};

} // anonymous namespace

// WtLatencyUFT测试套件
class WtLatencyUFTTest : public ::testing::Test {
protected:
    void SetUp() override {
        uft_latency = std::make_unique<MockWtLatencyUFT>();
    }

    void TearDown() override {
        if (uft_latency) {
            uft_latency->stop_measuring();
        }
        uft_latency.reset();
    }

    std::unique_ptr<MockWtLatencyUFT> uft_latency;
};

// WtLatencyHFT测试套件
class WtLatencyHFTTest : public ::testing::Test {
protected:
    void SetUp() override {
        hft_latency = std::make_unique<MockWtLatencyHFT>();
    }

    void TearDown() override {
        if (hft_latency) {
            hft_latency->stop_monitoring();
        }
        hft_latency.reset();
    }

    std::unique_ptr<MockWtLatencyHFT> hft_latency;
};

// WtLatencyUFT基本功能测试
TEST_F(WtLatencyUFTTest, BasicFunctionality) {
    // 测试初始状态
    EXPECT_FALSE(uft_latency->is_initialized()) << "UFT延迟测量器初始状态应为未初始化";
    EXPECT_FALSE(uft_latency->is_measuring()) << "初始状态应为未测量";
    
    // 测试初始化
    EXPECT_TRUE(uft_latency->init("/tmp/config.json")) << "UFT延迟测量器初始化应该成功";
    EXPECT_TRUE(uft_latency->is_initialized()) << "初始化后状态应为已初始化";
    
    // 测试开始测量
    EXPECT_TRUE(uft_latency->start_measuring()) << "开始测量应该成功";
    EXPECT_TRUE(uft_latency->is_measuring()) << "开始测量后状态应为测量中";
}

TEST_F(WtLatencyUFTTest, LatencyPointRecording) {
    uft_latency->init("/tmp/config.json");
    uft_latency->start_measuring();
    
    // 记录延迟点
    EXPECT_TRUE(uft_latency->record_latency_point(LatencyPoint::ORDER_RECEIVED, "order_1")) 
        << "记录订单接收点应该成功";
    
    std::this_thread::sleep_for(std::chrono::microseconds(100));
    
    EXPECT_TRUE(uft_latency->record_latency_point(LatencyPoint::ORDER_VALIDATED, "order_1")) 
        << "记录订单验证点应该成功";
    
    std::this_thread::sleep_for(std::chrono::microseconds(50));
    
    EXPECT_TRUE(uft_latency->record_latency_point(LatencyPoint::ORDER_SENT, "order_1")) 
        << "记录订单发送点应该成功";
    
    // 检查记录数量
    EXPECT_EQ(uft_latency->get_record_count(), 3) << "应该记录3个延迟点";
}

TEST_F(WtLatencyUFTTest, LatencyCalculation) {
    uft_latency->init("/tmp/config.json");
    uft_latency->start_measuring();
    
    // 模拟订单处理流程 - 使用相同的标签来匹配记录
    std::string tag = "order_test";
    
    // 记录订单接收
    EXPECT_TRUE(uft_latency->record_latency_point(LatencyPoint::ORDER_RECEIVED, tag));
    
    // 模拟处理时间
    std::this_thread::sleep_for(std::chrono::microseconds(200));
    
    // 记录订单发送
    EXPECT_TRUE(uft_latency->record_latency_point(LatencyPoint::ORDER_SENT, tag));
    
    // 验证记录是否成功创建
    EXPECT_EQ(uft_latency->get_record_count(), 2) << "应该有2条记录";
    
    // 使用基于标签的延迟计算
    double latency = uft_latency->calculate_latency_by_tag(
        LatencyPoint::ORDER_RECEIVED, LatencyPoint::ORDER_SENT, tag);
    
    EXPECT_GT(latency, 0) << "延迟应该大于0";
    EXPECT_GT(latency, 100) << "延迟应该大于100微秒"; // 考虑到我们sleep了200微秒
    EXPECT_LT(latency, 1000) << "延迟应该小于1000微秒"; // 合理的上限
    
    // 验证统计功能
    LatencyStats stats = uft_latency->get_latency_stats(
        LatencyPoint::ORDER_RECEIVED, LatencyPoint::ORDER_SENT);
    
    EXPECT_EQ(stats.sample_count, 1) << "应该有1个延迟样本";
    EXPECT_GT(stats.avg_latency_us, 100) << "平均延迟应该大于100微秒";
}

TEST_F(WtLatencyUFTTest, LatencyStatistics) {
    uft_latency->init("/tmp/config.json");
    uft_latency->start_measuring();
    
    // 模拟多个订单的处理 - 使用唯一标签确保每个样本都能被正确匹配
    for (int i = 0; i < 10; ++i) {
        std::string tag = "batch_test_" + std::to_string(i);
        uft_latency->record_latency_point(LatencyPoint::ORDER_RECEIVED, tag);
        
        // 模拟不同的处理时间
        std::this_thread::sleep_for(std::chrono::microseconds(50 + i * 10));
        
        uft_latency->record_latency_point(LatencyPoint::ORDER_VALIDATED, tag);
    }
    
    // 获取统计信息
    LatencyStats stats = uft_latency->get_latency_stats(
        LatencyPoint::ORDER_RECEIVED, LatencyPoint::ORDER_VALIDATED);
    
    EXPECT_EQ(stats.sample_count, 10) << "样本数量应为10";
    EXPECT_GT(stats.avg_latency_us, 0) << "平均延迟应大于0";
    EXPECT_GE(stats.max_latency_us, stats.min_latency_us) << "最大延迟应大于等于最小延迟";
    EXPECT_GE(stats.p95_latency_us, stats.p50_latency_us) << "95分位延迟应大于等于50分位延迟";
}

// WtLatencyHFT基本功能测试
TEST_F(WtLatencyHFTTest, BasicFunctionality) {
    // 测试初始状态
    EXPECT_FALSE(hft_latency->is_initialized()) << "HFT延迟监控器初始状态应为未初始化";
    EXPECT_FALSE(hft_latency->is_monitoring()) << "初始状态应为未监控";
    
    // 测试初始化
    EXPECT_TRUE(hft_latency->init("/tmp/config.json", 1000)) << "HFT延迟监控器初始化应该成功";
    EXPECT_TRUE(hft_latency->is_initialized()) << "初始化后状态应为已初始化";
    
    // 测试开始监控
    EXPECT_TRUE(hft_latency->start_monitoring()) << "开始监控应该成功";
    EXPECT_TRUE(hft_latency->is_monitoring()) << "开始监控后状态应为监控中";
}

TEST_F(WtLatencyHFTTest, NetworkLatencyRecording) {
    hft_latency->init("/tmp/config.json", 100);
    hft_latency->start_monitoring();
    
    const std::string endpoint = "test_exchange";
    
    // 记录网络延迟
    for (int i = 0; i < 50; ++i) {
        double latency = 100.0 + i * 2.0; // 100-198微秒
        hft_latency->record_network_latency(latency, endpoint);
    }
    
    // 获取统计信息
    LatencyStats stats = hft_latency->get_network_stats(endpoint);
    
    EXPECT_EQ(stats.sample_count, 50) << "网络延迟样本数量应为50";
    EXPECT_DOUBLE_EQ(stats.min_latency_us, 100.0) << "最小网络延迟应为100.0";
    EXPECT_DOUBLE_EQ(stats.max_latency_us, 198.0) << "最大网络延迟应为198.0";
    EXPECT_GT(stats.avg_latency_us, 100.0) << "平均网络延迟应大于100.0";
}

TEST_F(WtLatencyHFTTest, ProcessingLatencyRecording) {
    hft_latency->init("/tmp/config.json", 100);
    hft_latency->start_monitoring();
    
    const std::string component = "order_engine";
    
    // 记录处理延迟
    for (int i = 0; i < 30; ++i) {
        double latency = 10.0 + i * 0.5; // 10-24.5微秒
        hft_latency->record_processing_latency(latency, component);
    }
    
    // 获取统计信息
    LatencyStats stats = hft_latency->get_processing_stats(component);
    
    EXPECT_EQ(stats.sample_count, 30) << "处理延迟样本数量应为30";
    EXPECT_DOUBLE_EQ(stats.min_latency_us, 10.0) << "最小处理延迟应为10.0";
    EXPECT_DOUBLE_EQ(stats.max_latency_us, 24.5) << "最大处理延迟应为24.5";
    EXPECT_GT(stats.avg_latency_us, 10.0) << "平均处理延迟应大于10.0";
}

TEST_F(WtLatencyHFTTest, MonitoringListManagement) {
    hft_latency->init("/tmp/config.json", 100);
    hft_latency->start_monitoring();
    
    // 记录不同端点和组件的延迟
    hft_latency->record_network_latency(50.0, "exchange_a");
    hft_latency->record_network_latency(60.0, "exchange_b");
    hft_latency->record_processing_latency(15.0, "component_x");
    hft_latency->record_processing_latency(20.0, "component_y");
    
    // 获取监控列表
    std::vector<std::string> endpoints = hft_latency->get_monitored_endpoints();
    std::vector<std::string> components = hft_latency->get_monitored_components();
    
    EXPECT_EQ(endpoints.size(), 2) << "应该监控2个端点";
    EXPECT_EQ(components.size(), 2) << "应该监控2个组件";
    
    // 检查端点列表
    EXPECT_NE(std::find(endpoints.begin(), endpoints.end(), "exchange_a"), endpoints.end()) 
        << "应该包含exchange_a";
    EXPECT_NE(std::find(endpoints.begin(), endpoints.end(), "exchange_b"), endpoints.end()) 
        << "应该包含exchange_b";
    
    // 检查组件列表
    EXPECT_NE(std::find(components.begin(), components.end(), "component_x"), components.end()) 
        << "应该包含component_x";
    EXPECT_NE(std::find(components.begin(), components.end(), "component_y"), components.end()) 
        << "应该包含component_y";
}

// 性能测试
TEST_F(WtLatencyUFTTest, PerformanceCharacteristics) {
    uft_latency->init("/tmp/config.json");
    uft_latency->start_measuring();
    
    const int record_count = 10000;
    auto start_time = std::chrono::high_resolution_clock::now();
    
    // 大量记录延迟点
    for (int i = 0; i < record_count; ++i) {
        uft_latency->record_latency_point(LatencyPoint::ORDER_RECEIVED, "perf_test");
        uft_latency->record_latency_point(LatencyPoint::ORDER_SENT, "perf_test");
    }
    
    auto end_time = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end_time - start_time);
    
    std::cout << "UFT延迟记录性能测试: " << record_count * 2 << "个记录耗时 " 
              << duration.count() << "微秒" << std::endl;
    
    EXPECT_LT(duration.count(), 100000) << "10000次记录应在100ms内完成";
    EXPECT_EQ(uft_latency->get_record_count(), record_count * 2) << "记录数量应正确";
}

// 并发测试
TEST_F(WtLatencyUFTTest, ConcurrentRecording) {
    uft_latency->init("/tmp/config.json");
    uft_latency->start_measuring();
    
    const int num_threads = 4;
    const int records_per_thread = 1000;
    std::atomic<int> success_count{0};
    
    std::vector<std::thread> threads;
    
    for (int t = 0; t < num_threads; ++t) {
        threads.emplace_back([&, t]() {
            for (int i = 0; i < records_per_thread; ++i) {
                std::string tag = "thread_" + std::to_string(t) + "_" + std::to_string(i);
                if (uft_latency->record_latency_point(LatencyPoint::ORDER_RECEIVED, tag)) {
                    success_count++;
                }
            }
        });
    }
    
    for (auto& thread : threads) {
        thread.join();
    }
    
    std::cout << "UFT并发记录测试: 成功记录 " << success_count.load() << " 个延迟点" << std::endl;
    EXPECT_EQ(success_count.load(), num_threads * records_per_thread) << "所有记录都应成功";
    EXPECT_EQ(uft_latency->get_record_count(), success_count.load()) << "记录数量应匹配";
}

// 边界条件测试
TEST_F(WtLatencyUFTTest, BoundaryConditions) {
    // 测试未初始化状态
    EXPECT_FALSE(uft_latency->start_measuring()) << "未初始化时开始测量应失败";
    EXPECT_FALSE(uft_latency->record_latency_point(LatencyPoint::ORDER_RECEIVED)) 
        << "未测量时记录应失败";
    
    // 初始化但未开始测量
    uft_latency->init("/tmp/config.json");
    EXPECT_FALSE(uft_latency->record_latency_point(LatencyPoint::ORDER_RECEIVED)) 
        << "未开始测量时记录应失败";
    
    // 开始测量后
    uft_latency->start_measuring();
    EXPECT_TRUE(uft_latency->record_latency_point(LatencyPoint::ORDER_RECEIVED)) 
        << "开始测量后记录应成功";
    
    // 停止测量后
    uft_latency->stop_measuring();
    EXPECT_FALSE(uft_latency->record_latency_point(LatencyPoint::ORDER_SENT)) 
        << "停止测量后记录应失败";
}

TEST_F(WtLatencyHFTTest, BoundaryConditions) {
    // 测试未初始化状态
    EXPECT_FALSE(hft_latency->start_monitoring()) << "未初始化时开始监控应失败";
    
    // 初始化后测试
    hft_latency->init("/tmp/config.json", 10);
    hft_latency->start_monitoring();
    
    // 测试空端点和组件名
    hft_latency->record_network_latency(100.0, "");
    hft_latency->record_processing_latency(50.0, "");
    
    LatencyStats empty_stats = hft_latency->get_network_stats("");
    EXPECT_EQ(empty_stats.sample_count, 1) << "空端点名应该能记录";
    
    // 测试缓冲区溢出
    for (int i = 0; i < 20; ++i) {
        hft_latency->record_network_latency(i * 10.0, "overflow_test");
    }
    
    LatencyStats overflow_stats = hft_latency->get_network_stats("overflow_test");
    EXPECT_LE(overflow_stats.sample_count, 10) << "缓冲区大小应该被限制";
}

// 集成测试
TEST(LatencyModulesIntegrationTest, UFTAndHFTIntegration) {
    auto uft_latency = std::make_unique<MockWtLatencyUFT>();
    auto hft_latency = std::make_unique<MockWtLatencyHFT>();
    
    // 初始化两个模块
    EXPECT_TRUE(uft_latency->init("/tmp/config.json")) << "UFT模块初始化失败";
    EXPECT_TRUE(hft_latency->init("/tmp/config.json", 1000)) << "HFT模块初始化失败";
    
    // 启动监控
    EXPECT_TRUE(uft_latency->start_measuring()) << "UFT测量启动失败";
    EXPECT_TRUE(hft_latency->start_monitoring()) << "HFT监控启动失败";
    
    // 模拟交易流程
    const int order_count = 100;
    
    for (int i = 0; i < order_count; ++i) {
        // UFT记录订单处理延迟点
        uft_latency->record_latency_point(LatencyPoint::ORDER_RECEIVED, "order_" + std::to_string(i));
        
        // 模拟网络延迟
        double network_latency = 50.0 + (i % 50) * 2.0;
        hft_latency->record_network_latency(network_latency, "main_exchange");
        
        // 模拟处理时间
        std::this_thread::sleep_for(std::chrono::microseconds(10 + i % 20));
        
        // UFT记录订单发送
        uft_latency->record_latency_point(LatencyPoint::ORDER_SENT, "order_" + std::to_string(i));
        
        // HFT记录处理延迟
        double processing_latency = 10.0 + (i % 30) * 0.5;
        hft_latency->record_processing_latency(processing_latency, "order_processor");
    }
    
    // 等待一些自动监控数据
    std::this_thread::sleep_for(std::chrono::milliseconds(500));
    
    // 检查UFT统计
    LatencyStats uft_stats = uft_latency->get_latency_stats(
        LatencyPoint::ORDER_RECEIVED, LatencyPoint::ORDER_SENT);
    
    // 检查HFT统计
    LatencyStats network_stats = hft_latency->get_network_stats("main_exchange");
    LatencyStats processing_stats = hft_latency->get_processing_stats("order_processor");
    
    // 验证结果
    EXPECT_EQ(uft_stats.sample_count, order_count) << "UFT应该记录" << order_count << "个样本";
    EXPECT_EQ(network_stats.sample_count, order_count) << "网络延迟应该记录" << order_count << "个样本";
    EXPECT_GE(processing_stats.sample_count, order_count) << "处理延迟应该记录至少" << order_count << "个样本";
    
    std::cout << "延迟模块集成测试通过" << std::endl;
    std::cout << "UFT订单处理延迟统计:" << std::endl;
    std::cout << "  平均: " << uft_stats.avg_latency_us << "μs" << std::endl;
    std::cout << "  P95: " << uft_stats.p95_latency_us << "μs" << std::endl;
    std::cout << "HFT网络延迟统计:" << std::endl;
    std::cout << "  平均: " << network_stats.avg_latency_us << "μs" << std::endl;
    std::cout << "  P95: " << network_stats.p95_latency_us << "μs" << std::endl;
    std::cout << "HFT处理延迟统计:" << std::endl;
    std::cout << "  平均: " << processing_stats.avg_latency_us << "μs" << std::endl;
    std::cout << "  P95: " << processing_stats.p95_latency_us << "μs" << std::endl;
    
    // 清理
    uft_latency->stop_measuring();
    hft_latency->stop_monitoring();
}
